package cn.kaiux.bigdata.homework.week05_06

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.FileSystem

import java.net.URI
import scala.collection.mutable

/**
 * @author kaiux@foxmail.com
 * @date 2022/6/11 13:41
 */
class FileSystemObjectCacher(hadoopConfiguration: Configuration) {

  private val cache: mutable.Map[URI, FileSystem] = mutable.Map.empty

  def getOrCreate(uri: URI): FileSystem = get(uri) match {
    case Some(fs) => fs
    case None =>
      val fs = FileSystem.get(uri, hadoopConfiguration)
      cache.update(fs.getUri, fs)
      fs
  }

  def get(uri: URI): Option[FileSystem] = cache.collectFirst {
    case (u, f) if FileUtils.uriIsChild(u.resolve("/"), uri) => f
  }

}

